import cv2 as cv
import numpy as np
from imutils import perspective
from imutils import contours
import imutils
from scipy.spatial import distance as dist

# 参照物尺寸mm
BASE_SIZE = 87
# 面积小于 像素将被忽略
AREA_FILTER = 5000
# 边缘查找灰度值范围
CANNY_MIN = 50
CANNY_MAX = 100

def midpoint(ptA, ptB):
    return ((ptA[0] + ptB[0]) * 0.5, (ptA[1] + ptB[1]) * 0.5)

image = cv.imread('measuring/measure.jpg')
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
gray = cv.GaussianBlur(gray, (7, 7), 0)

edged = cv.Canny(gray, CANNY_MIN, CANNY_MAX)
edged = cv.dilate(edged, None, iterations=1)
edged = cv.erode(edged, None,iterations = 1)

cnts, hierarchy = cv.findContours(edged.copy(), cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE)

(cnts, _) = contours.sort_contours(cnts)
pixelsPerMetric = None
for c in cnts:
    if cv.contourArea(c) < AREA_FILTER:
        continue

    orig = image.copy()
    box = cv.minAreaRect(c)
    box = cv.cv.BoxPoints(box) if imutils.is_cv2() else cv.boxPoints(box)
    box = np.array(box, dtype="int")
    box = perspective.order_points(box)
    cv.drawContours(orig, [box.astype("int")], -1, (0, 255, 0), 2)

    for (x, y) in box:
        cv.circle(orig, (int(x), int(y)), 5, (0, 0, 255), -1)

    (tl, tr, br, bl) = box
    (tltrX, tltrY) = midpoint(tl, tr)
    (blbrX, blbrY) = midpoint(bl, br)
    
    (tlblX, tlblY) = midpoint(tl, bl)
    (trbrX, trbrY) = midpoint(tr, br)

    dA = dist.euclidean((tltrX, tltrY), (blbrX, blbrY))
    dB = dist.euclidean((tlblX, tlblY), (trbrX, trbrY))
    print(dA, dB)
    if pixelsPerMetric is None:
        pixelsPerMetric = dB / BASE_SIZE

    dimA = dA / pixelsPerMetric
    dimB = dB / pixelsPerMetric

    cv.putText(orig, "{:.1f}mm".format(dimB),
        (int(tltrX - 15), int(tltrY - 10)), cv.FONT_HERSHEY_SIMPLEX,
        0.65, (255, 255, 255), 2)
    cv.putText(orig, "{:.1f}mm".format(dimA),
        (int(trbrX + 10), int(trbrY)), cv.FONT_HERSHEY_SIMPLEX,
        0.65, (255, 255, 255), 2)

    cv.imshow('frame', orig)
    cv.waitKey(0)

cv.destroyAllWindows()
